package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/region")
public class RegionController {
    @Autowired
    private IRegionService regionService;

    @RequestMapping("/list")
    public String list() {
        regionService.listAll();
        return "/region/list";
    }

    @RequestMapping("/listByParentId")
    @ResponseBody
    public List listByParentId(Long parentId, String type) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Region> regions = regionService.selectByPrentId(parentId);
        if (parentId != null && "table".equals(type)) {
            return regions;
        } else {
            for (Region region : regions) {
                list.add(region.toTreeMap());
            }
        }

        return list;
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Region region) {
        JsonResult result = new JsonResult();
        try {
            result.setData(regionService.saveOrUpdate(region));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/changeState")
    @ResponseBody
    public JsonResult changeState(Long id, Integer state) {
        JsonResult result = new JsonResult();
        try {
            regionService.changeState(id, state);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
